import React, { FormEvent, FormEventHandler, useEffect, useState } from "react";
import {
  DownloadOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";
import {
  Button,
  Form,
  Input,
  Pagination,
  Space,
  Table,
  Tag,
  Modal,
  message,
  Upload,
  UploadProps,
  Radio,
  DatePicker,
  Avatar,
} from "antd";
import "./index.less";
import { ColumnsType } from "antd/es/table";
import {
  departmentPage,
  departmentCreate,
  departmentGetOne,
  departmentSetStatus,
} from "../../api/department";
import { RcFile, UploadChangeParam, UploadFile } from "antd/es/upload";
import { IDepartment } from "@/types/department";
import { IUploadFaceInfo } from "@/types/common";
import { departmentDel } from "../../api/department";

const { confirm } = Modal;
const DepartmentPage = () => {
  const [name, setName] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [pageInfo, setPageInfo] = useState({ page: 1, pageSize: 10, total: 0 });

  const [data, setData] = useState<IDepartment[]>([]);

  const [loading, setLoading] = useState(false);

  const [moduleForm, setModuleForm] = useState<Partial<IDepartment>>({
    name: "",
    avatar: "",
  });

  const columns: ColumnsType<IDepartment> = [
    {
      title: "部门名",
      dataIndex: "name",
    },

    {
      title: "状态",
      dataIndex: "status",
      render(value, record) {
        return (
          <Button type={value === 1 ? "link" : "text"} danger={!value}>
            {value === 1 ? "启用" : "禁用"}
          </Button>
        );
      },
    },
    {
      title: "头像",
      dataIndex: "avatar",
      render(value, record) {
        return (
          <Avatar
            src={
              value ||
              "https://tse4-mm.cn.bing.net/th/id/OIP-C.y2CeSO5xZJ1SjSskl1dqzwHaEo?w=279&h=180&c=7&r=0&o=5&dpr=2&pid=1.7"
            }
          />
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      render(value, record, index) {
        return new Date(value).toLocaleString();
      },
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      render(value, record, index) {
        return new Date(value).toLocaleString();
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEditRow(record.id)}>
            修改
          </Button>
          <Button
            type="link"
            onClick={() => handleStatusRow(record.id, record.status)}
          >
            {record.status === 0 ? "启用" : "禁用"}
          </Button>
          <Button type="text" danger onClick={() => handleDelRow(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // To disable submit button at the beginning.
  useEffect(() => {
    queryPage();
  }, [pageInfo.page, pageInfo.pageSize]);

  const queryPage = async () => {
    const pageInfoRes = await departmentPage(
      pageInfo.page,
      pageInfo.pageSize,
      name
    );
    if (pageInfoRes) {
      const { total, records, page, pageSize } = pageInfoRes;
      setData(records);
      setPageInfo({
        total,
        page,
        pageSize,
      });
    }
  };

  const handleOk = async () => {
    let err = "";
    for (const k in moduleForm) {
      // @ts-ignore
      if (moduleForm[k] === "") {
        err = k;
        break;
      }
    }
    if (err) {
      message.error(err);
    } else {
      const res = await departmentCreate(moduleForm);
      if (res) {
        setIsModalOpen(false);
        queryPage();
      }
    }
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const changeInput = (e: FormEvent<HTMLInputElement>, name: string) => {
    setModuleForm({
      ...moduleForm,
      [name]: (e.target as HTMLInputElement).value,
    });
  };

  /**
   *
   * @returns 新增编辑模块
   */
  const addAndEditModule = () => {
    return (
      <Modal
        title="新增编辑"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form className="department-module-form">
          <div className="ant-form-item css-dev-only-do-not-override-sk7ap8">
            <div className="ant-row ant-form-item-row css-dev-only-do-not-override-sk7ap8">
              <div className="ant-col ant-form-item-label css-dev-only-do-not-override-sk7ap8">
                <label>姓名</label>
              </div>
              <Input
                style={{ flex: 1 }}
                onChange={(e) => changeInput(e, "name")}
                value={moduleForm.name}
                placeholder="请输入部门名称～"
              />
            </div>
          </div>
          <Form.Item label="头像">
            <Upload
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              maxCount={1}
              action="/api/v1/base/uploadOSS"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {moduleForm.avatar ? (
                <img
                  src={moduleForm.avatar}
                  alt="avatar"
                  style={{ width: "100%" }}
                />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      setLoading(false);
      const res: IUploadFaceInfo = info.file.response.data;
      if (res) {
        setModuleForm({
          ...moduleForm,
          avatar: res.url,
        });
      } else {
        message.error(info.file.response.message);
      }
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };

  const beforeUpload = async (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  // 删除
  const handleDelRow = (id: string) => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: "确定执行此操作么?",
      async onOk() {
        const res = await departmentDel(id);
        if (res) {
          queryPage();
        }
      },
      onCancel() {
        message.warning("取消操作");
      },
    });
  };

  // 启用  禁用
  const handleStatusRow = async (id: string, status: number) => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: "确定执行此操作么?",
      async onOk() {
        const res = await departmentSetStatus(status === 0 ? 1 : 0, id);
        if (res) {
          if (pageInfo.page === 1 && pageInfo.pageSize === 10) {
            queryPage();
          } else {
            setPageInfo({ ...pageInfo, page: 1, pageSize: 10 });
          }
        }
      },
      onCancel() {
        message.warning("取消操作");
      },
    });
  };
  // 修改
  const handleEditRow = async (id: string) => {
    const res = await departmentGetOne(id);
    if (res) {
      setModuleForm(res);
    }

    setIsModalOpen(true);
  };

  // 搜索区域
  const searchElement = () => {
    return (
      <div className="department-head">
        <Form layout="inline">
          <Form.Item name="name" label="姓名">
            <Input
              value={name}
              onInput={(e) => setName((e.target as HTMLInputElement).value)}
              placeholder="请输入姓名～"
            />
          </Form.Item>

          <Form.Item shouldUpdate>
            {() => (
              <Button type="primary" onClick={() => queryPage()}>
                搜索
              </Button>
            )}
          </Form.Item>
        </Form>
        <div>
          <Button type="primary" onClick={() => setIsModalOpen(true)}>
            新增
          </Button>
        </div>
      </div>
    );
  };

  // 表格区域
  const tableElement = () => {
    return (
      <div className="margin-top-22px">
        <Table
          dataSource={data}
          columns={columns}
          rowKey="id"
          pagination={{
            total: pageInfo.total,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: (page, pageSize) => {
              setPageInfo({
                ...pageInfo,
                page,
                pageSize,
              });
            },
            showTotal: (total) => `共 ${total} 条数据`,
          }}
        />
      </div>
    );
  };
  return (
    <>
      {searchElement()}
      {tableElement()}
      {addAndEditModule()}
    </>
  );
};

export default DepartmentPage;
